package com.gombe.credit.app.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonDialog
import com.gombe.credit.app.databinding.DialogGombeCreditStepWalletAddBinding
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.ui.adapter.AdapterGombeCreditStepWalletType
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.decoration.GridSpacingItemDecoration
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import com.gombe.credit.app.weight.font.LexendMediumEditText
import org.json.JSONObject

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/21 13:45
 * @Annotation：绑卡dialog
 */
class DialogGombeCreditWalletAdd: CommonDialog {
    private lateinit var binding: DialogGombeCreditStepWalletAddBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    //开始选择时间
    private var startTime = 0L;

    var itemAdapter: AdapterGombeCreditStepWalletType? = null

    constructor(context: Context) : super(context) {}
    constructor(context: Context, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun takeGombeCreditRootView(): View {
        binding = DialogGombeCreditStepWalletAddBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initGombeCreditView() {
        initWalletAccountTypeListView()
        showTypeDefaultView()
        checkGombeCreditWalletSubmitStatus()
    }

    override fun initGombeCreditListener() {
        setOnClickListener(binding.imageClose)
        setOnClickListener(binding.buttonWalletAccountSubmit)

        binding.editWalletAccount.addTextChangedListener(ITextWatcher)
        binding.editWalletAccountAgain.addTextChangedListener(ITextWatcher)
        binding.editWalletAccount.setInputFocusChangeListener(IEditFocusChangeListener)
        binding.editWalletAccountAgain.setInputFocusChangeListener(IEditFocusChangeListener)
        binding.editWalletAccount.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.editWalletAccount.clearFocus()
                true
            }
            false
        }
        binding.editWalletAccountAgain.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.editWalletAccountAgain.clearFocus()
                true
            }
            false
        }
    }

    override fun takeGombeCreditData() {
        val bindList = arrayListOf<JSONObject>()
        val customize = GombeCreditConfigsHelper.takeGombeCreditConfigData()
        if (customize != null){
            val walletChannels = customize.optJSONArray("walletChannels")
            if (walletChannels != null && walletChannels.length() > 0){
                for (i in 0..<walletChannels.length()){
                    val item = walletChannels.optJSONObject(i)
                    item.put("isSelect", false)
                    bindList.add(item)
                }
            }
        }
        itemAdapter?.data = bindList
    }

    override fun onGombeCreditViewClick(v: View?) {
        when(v?.id){
            R.id.imageClose -> {//关闭
                dismiss()
            }
            R.id.buttonWalletAccountSubmit -> {//提交
                val typeObj = getSelectTypeItem() ?: return
                if (takeGombeCreditWalletMobile() != takeGombeCreditWalletMobileComplete()){
                    showTypeErrorView()
                    return
                }
                val duration = System.currentTimeMillis() - startTime
                val submitRemark = "${takeGombeCreditWalletMobile()}$$$duration"
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_WALLET_ADD_SUBMIT,submitRemark)
                if(mCallback != null){
                    mCallback?.onSubmitParams(typeObj,takeGombeCreditWalletMobile())
                }
                dismiss()
            }
        }
    }

    /**
     * 初始化类型列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initWalletAccountTypeListView() {
        val layoutManager = GridLayoutManager(context,2)
        binding.walletAccountTypeListView.layoutManager = layoutManager
        itemAdapter = AdapterGombeCreditStepWalletType(binding.walletAccountTypeListView)
        val leftDecoration = GombeCreditDensityUtil.dp2px(10f)
        binding.walletAccountTypeListView.addItemDecoration(GridSpacingItemDecoration(2, leftDecoration, false))
        binding.walletAccountTypeListView.adapter = itemAdapter
        binding.walletAccountTypeListView.itemAnimator = DefaultItemAnimator()
        itemAdapter?.setOnItemChildClickListener { _, childView, position ->
            itemAdapter?.let {
                val model = it.getItem(position)
                if (childView.id == R.id.walletTypeLayout) {//切换item
                    for (i in 0..<it.itemCount) {
                        val item = it.getItem(i)
                        if (i == position) {
                            item.put("isSelect", true)
                        } else {
                            item.put("isSelect", false)
                        }
                    }
                    it.notifyDataSetChanged()
                    checkGombeCreditWalletSubmitStatus()
                    addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_WALLET_ADD_TYPE_CHECK, model.optString("desc"))
                }
            }
        }
    }

    /**
     * 输入框监听
     */
    private val ITextWatcher = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            showTypeDefaultView()
            checkGombeCreditWalletSubmitStatus()
        }
    }

    /**
     * 焦点变化监听
     */
    private val IEditFocusChangeListener = object : LexendMediumEditText.IInputFocusChangeListener{
        override fun onFocusChange(v: View?, hasFocus: Boolean) {
        }
        override fun onCompleteAction(v: View?, remark: String) {
            var mobile = ""
            if (v?.id == R.id.editWalletAccount){
                mobile = takeGombeCreditWalletMobile()
            } else {
                mobile = takeGombeCreditWalletMobileComplete()
            }
            if (mobile.isNotEmpty()){
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.USER_WALLET_ADD_MOBILE,remark)
            }
        }
    }

    /**
     * 设置默认样式
     */
    private fun showTypeDefaultView(){
        binding.editWalletAccount.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.gombe_credit_FFF9F9F7))
            .setStrokeColor(getColor(R.color.gombe_credit_FFF9F9F7))
            .intoBackground()
        binding.editWalletAccount.setTextColor(getColor(R.color.black))
        binding.editWalletAccountAgain.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.gombe_credit_FFF9F9F7))
            .setStrokeColor(getColor(R.color.gombe_credit_FFF9F9F7))
            .intoBackground()
        binding.editWalletAccountAgain.setTextColor(getColor(R.color.black))
        binding.walletAccountErrorLayout.visibility = View.INVISIBLE
    }

    /**
     * 设置号码错误提示
     */
    private fun showTypeErrorView(){
        binding.editWalletAccount.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.transparent))
            .setStrokeColor(getColor(R.color.gombe_credit_FFE55050))
            .intoBackground()
        binding.editWalletAccount.setTextColor(getColor(R.color.gombe_credit_FFE55050))
        binding.editWalletAccountAgain.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.transparent))
            .setStrokeColor(getColor(R.color.gombe_credit_FFE55050))
            .intoBackground()
        binding.editWalletAccountAgain.setTextColor(getColor(R.color.gombe_credit_FFE55050))
        binding.walletAccountErrorLayout.visibility = View.VISIBLE
    }

    /**
     * 切换Ajouter按钮是否可点击
     */
    fun checkGombeCreditWalletSubmitStatus(){
        if (getSelectTypeItem() != null && takeGombeCreditWalletMobile().isNotEmpty() && takeGombeCreditWalletMobileComplete().isNotEmpty() && (takeGombeCreditWalletMobile() == takeGombeCreditWalletMobileComplete())){
            binding.buttonWalletAccountSubmit.isEnabled = true
        } else {
            binding.buttonWalletAccountSubmit.isEnabled = false
        }
    }

    /**
     * 获取选择的账户类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var obj: JSONObject? = null
        itemAdapter?.let {
            for (item in it.data) {
                if (item.optBoolean("isSelect", false)){
                    obj = item
                    break
                }
            }
        }
        return obj
    }

    /**
     * 获取输入的手机号码
     */
    private fun takeGombeCreditWalletMobile(): String{
        return binding.editWalletAccount.text.toString()
    }

    /**
     * 获取确认手机号码
     */
    private fun takeGombeCreditWalletMobileComplete(): String{
        return binding.editWalletAccountAgain.text.toString()
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
        //确认
        fun onSubmitParams(typeObj: JSONObject,phoneNumber: String)
    }

    override fun show() {
        super.show()
        startTime = System.currentTimeMillis()
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_DIALOG.USER_WALLET_ADD_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_DIALOG.USER_WALLET_ADD_DISMISS,eventRemark)
    }
}